package response

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

type Response struct {
	Context *gin.Context
	// 响应体
	Body struct {
		Code    int         `json:"code"`
		Message string      `json:"message"`
		Meta    interface{} `json:"-"` // 关闭meta响应字段
		Data    interface{} `json:"data"`
	}
}

const (
	SUCCESS = 200
	FAILED  = 0
)

func New(c *gin.Context) *Response {
	return &Response{
		Context: c,
	}
}

func (r *Response) Success() {
	r.Json(http.StatusOK, SUCCESS, "SUCCESS", nil)
}

func (r *Response) SuccessWithMessage(message string) {
	r.Json(http.StatusOK, SUCCESS, message, nil)
}

func (r *Response) SuccessWithData(data interface{}) {
	r.Json(http.StatusOK, SUCCESS, "SUCCESS", data)
}

// SuccessWithDetailed 响应成功
func (r *Response) SuccessWithDetailed(data interface{}, message string) {
	r.Json(http.StatusOK, SUCCESS, message, data)
}

func (r *Response) Fail() {
	r.Json(http.StatusOK, FAILED, "ERROR", nil)
}

func (r *Response) FailWithCode(code int) {
	r.Json(http.StatusOK, code, "ERROR", nil)
}

func (r *Response) FailWithMessage(code int, message string) {
	r.Json(http.StatusOK, code, message, nil)
}

// FailWithDetailed 响应失败
func (r *Response) FailWithDetailed(code int, message string, data interface{}) {
	r.Json(http.StatusOK, code, message, data)
}

// Json    响应JSON
// status  HTTP状态，如：http.StatusOK
// code    响应码
// message 错误信息
// data    响应结果
func (r *Response) Json(status int, code int, message string, data interface{}) {
	r.SetBody(code, message, data)
	r.Context.JSON(status, r.Body)
	r.Context.Abort()
}

// Meta 设置Meta
func (r *Response) Meta(data interface{}) *Response {
	r.Body.Meta = data
	return r
}

// SetBody 设置Body
func (r *Response) SetBody(code int, message string, data interface{}) {
	defaultData := map[string]interface{}{}
	// Data Default
	if data == nil {
		data = defaultData
	}
	// Meta Default
	if r.Body.Meta == nil {
		r.Body.Meta = defaultData
	}

	// Set Body
	r.Body.Code = code
	r.Body.Message = message
	r.Body.Data = data
}
